package com.xishu.controller;

import com.xishu.entity.User;
import com.xishu.entity.plat.UserShopMapping;
import com.xishu.entity.shop.Shop;
import com.xishu.response.ResponseData;
import com.xishu.response.ResponseStatus;
import com.xishu.response.VerifyUtil;
import com.xishu.service.CommonService;
import com.xishu.service.MappingService;
import com.xishu.service.ShopService;
import com.xishu.service.UserService;
import com.xishu.util.Tools;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@Api(description = "账号与分店的映射关系")
@RestController
public class UserShopMappingController implements Tools {
    private static Logger logger = LoggerFactory.getLogger(UserShopMappingController.class);
    private CommonService commonService = CommonService.getInstance();

    @PostMapping(value = ("/user/shop/mapping"), produces = ("application/json;charset=UTF-8"))
    @ApiOperation(value = "个人账号绑定分店")
    public ResponseData createOrModify(@RequestBody UserShopMapping userShopMapping) throws Exception {
        VerifyUtil.verify(() -> userShopMapping.getUserId() != null && userShopMapping.getShopId() != null);
        MappingService mappingService = MappingService.getInstance();
        Shop shop = ShopService.getInstance().findShopById(userShopMapping.getShopId());
        userShopMapping.setShopName(shop.getName());
        mappingService.createUserShopMapping(userShopMapping.getUserId(), userShopMapping.getShopId());
        return ResponseData.emptyResponse();
    }

    @DeleteMapping(value = ("/user/shop/mapping"), produces = ("application/json;charset=UTF-8"))
    @ApiOperation(value = "删除个人账号与分店的绑定关系")
    public ResponseData delete(@RequestBody UserShopMapping userShopMapping) throws Exception {
        //先查询对应的账号还剩下多少个分店
        Long mappingId = userShopMapping.getId();

        if (mappingId != null) {
            UserShopMapping mappingInEntity = commonService.findEntity(userShopMapping.getId(), UserShopMapping.class);
            Long userId = mappingInEntity.getUserId();
            UserShopMapping reqUserShopMapping = new UserShopMapping();
            reqUserShopMapping.setUserId(userId);
            Long count = commonService.count(reqUserShopMapping);
            VerifyUtil.verify(() -> getLong(count) >= 2, ResponseStatus.USER_AT_LEAST_ONE_SHOP);
        }

        return CommonService.getInstance().delete(userShopMapping);
    }

    @ApiOperation(value = "查询个人账号与分店的绑定关系")
    @PutMapping(value = ("/user/shop/mapping"), produces = ("application/json;charset=UTF-8"))
    public ResponseData search(@RequestBody UserShopMapping userShopMapping) throws Exception {
        return CommonService.getInstance().searchResponse(userShopMapping, (s) -> {
            //如果名称为空，那么从分店里面同步分店名称
            if (isEmpty(s.getShopName())) {
                Long shopId = s.getShopId();
                if (shopId != null) {
                    logger.info("shopId is {}, will sync shop name", shopId);
                    try {
                        Shop shop = CommonService.getInstance().findEntity(shopId, Shop.class);
                        if (shop != null) {
                            s.setShopName(shop.getName());
                            CommonService.getInstance().save(s);
                        }
                    } catch (Exception e) {
                        logger.error("e", e);
                    }
                }
            }

            //添加中英文显示
            Long shopId = s.getShopId();
            try {
                Shop shop = ShopService.getInstance().findShopById(shopId);
                s.setShopName_zh(shop.getName_zh());
                s.setShopName_en(shop.getName_en());
            } catch (Exception e) {
                logger.error("e", e);
            }

        }, (userShopMappingList) -> {
            List<Long> userIdListInDb = userShopMappingList.stream().map(s -> s.getUserId()).collect(Collectors.toList());
            //真实账号
            List<User> userListInDb = UserService.getInstance().findUserByIds(userIdListInDb);
            //经理账号
            List<Long> userIdList = userListInDb.stream().filter(s -> getBoolean(s.getShopManager()) || getBoolean(s.getCompanyManager())).map(s -> s.getId()).collect(Collectors.toList());
            //过滤出经理账号与分店的mapping
            userShopMappingList = userShopMappingList.stream().filter(s -> userIdList.contains(s.getUserId().longValue())).collect(Collectors.toList());
            //过滤ID为零的数据
            return userShopMappingList.stream().filter(p -> getLong(p.getShopId()) != 0 && getLong(p.getUserId()) != 0).collect(Collectors.toList());
        });
    }
}
